package com.ikun.common.easyexcel;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName EasyExcelUtil
 * @Description:
 * @CreateDate: 2024/8/5 11:30
 */
@Slf4j
public class EasyExcelUtil {
    /**
     * 导出单页Excel
     * @param response 响应对象
     * @param fileName 导出文件名
     * @param clazz 导出实体类
     * @param sheetName  导出sheet工作表名称
     * @param data 导出的数据集合
     */
    public static <T> void exportSingleSheetExcel(HttpServletResponse response, String fileName, Class<T> clazz, String sheetName, List<T> data) throws IOException {
        if (fileName.contains(".")) {
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);


    }

    /**
     * 导出多页Excel
     * @param response 响应对象
     * @param fileName 导出文件名
     * @param clazz 导出实体类
     * @param sheetNameList 导出sheet工作表名称集
     * @param data 导出的数据集合 二维集合 分别对应不同sheet页的数据
     */
    public static <T> void exportMultiSheetExcel(HttpServletResponse response, String fileName, Class<T> clazz, List<String> sheetNameList, List<List<T>> data) {
        if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
            fileName = fileName + ".xlsx";
        }
        //设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //调用easyexcel方法导出excel

        try {
            EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetNameList.get(0)).doWrite(data.get(0));
        } catch (IOException e) {
            log.error("导出Excel失败", e);
            throw new RuntimeException(e);
        }

    }
}
